# Lianstar-RS Board(UI) Logger by clonne/2023
import sys,traceback
from pathlib import Path
from datetime import datetime

class Const:
    LOGILE_PATH = Path("./log-board.txt")
    LOG_TRACEBACK_LIMIT = 64

class _m:
    _logfile = None
    ##[static]
    def make_block(text:str) -> str:
        column_time = datetime.now().isoformat(' ')
        return f"[{column_time}]{text}\n"
    ##[static]
    def write(text:str) -> None:
        assert _m._logfile.writable()
        _m._logfile.write(_m.make_block(text))
        _m._logfile.flush()
    ##[static]
    def write_traceback(etype, evalue, tb):
        _m.write(f"trackback.now -> {evalue}")
        traceback.print_exception(etype, evalue, tb, Const.LOG_TRACEBACK_LIMIT, _m._logfile)

def info(group:str, text:str) -> None:
    assert (len(group) > 0) and (len(text) > 0)
    _m.write(f"[Info {group}] {text}")

def warnning(group:str, text:str):
    assert (len(group) > 0) and (len(text) > 0)
    _m.write(f"[Warning {group}] {text}")

def error(group:str, text:str):
    assert (len(group) > 0) and (len(text) > 0)
    _m.write(f"[Error {group}] {text}")

def write_traceback_now():
    _m.write_traceback(*(sys.exc_info()))

def _raii_by_main_use_only():
    print("[logger raii]")
    assert not _m._logfile.closed
    _m._logfile.close()
    print("[logger has raii]")

def _init_by_main_use_only():
    print("[logger init]")
    if Const.LOGILE_PATH.is_file():
        print("[logger file clear]")
        with Const.LOGILE_PATH.open("wb") as f:
            f.truncate()
    _m._logfile = Const.LOGILE_PATH.open("a")
    print("[logger has initialized]")
